# encoding=UTF-8
from __future__ import division
import json
import logging
import time
import traceback
from flask import Flask, request
from flask_cors import *

from .mongodbconnection import mongodbcon
from .mongodbconnection import mongorobot
from .mysqlconn import conn
from .projectsql import robotsql
from ..zyrobot.quality_testing.quality_task import begin_quality_task, begin_quality_task_memcached, begin_single_quality_task, cycle_translate_voice, online_inspection, \
    online_inspection_hangup
from ..zyrobot.quality_testing.quality_task_sql import get_task_quality_service_data, get_taskid_quality_robot_data

app = Flask(__name__)
CORS(app, supports_credentials=True)
dbname = conn.basedbname
notcmpid = '无效的token！！或输入为空！！ '
web_logger = logging.getLogger('web_logger')

# IM机器人


@app.route('/getanswer')
def getanswer():
    global dbname
    try:
        if not 'token' in request.values or not 'text' in request.values \
                or not 'cid' in request.values or not 'channelid' in request.values \
                or not 'clevel' in request.values or not 'location' in request.values \
                or not 'who' in request.values:
            # cid = request.args['cid']      #会话编码
            return robotsql.backtype(0, -1, 1, '缺少参数！！请检查参数是否齐全！！')
        else:
            text = request.values['text']  # 查询文本
            token = request.values['token']  # token
            cid = request.values['cid']  # 会话编码
            channelid = request.values['channelid']  # 渠道编码
            clevel = request.values['clevel']  # 客户级别
            location = request.values['location']  # 地理位置

            who = request.values['who']  # 访问者，1：用户2：客服
            choiceback = ''

            if 'choiceback' in request.values:
                choiceback = request.values['choiceback']  # 上次返回的调用

            if 'dbname' in request.values:
                dbname = request.values['dbname']  # 不同的db
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            return robotsql.gr(cid, text, who, token, channelid, clevel, location, choiceback, dbname)
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        web_logger.error(traceback.format_exc())
        return robotsql.backtypeadd(0, -1, 1, "祝你生活愉快再见！！", '')


@app.route('/online_translate_voice')
def online_translate_voice():
    global dbname
    required_fields = ['quality_type',
                       'session_sort', 'voice_address', 'saleid']
    for required_field in required_fields:
        if required_field not in request.values:
            return robotsql.backresult(-1)
    quality_type = request.values.get('quality_type')
    session_sort = request.values.get('session_sort')
    voice_address = request.values.get('voice_address')
    saleid = request.values.get('saleid')

    datajson = robotsql.Voicerecognition(1, voice_address, time.time())
    data = json.loads(datajson)
    text = data['text']
    web_logger.info('quality_type:%s session_sort:%s voice_address:%s saleid:%s text:%s',
                    quality_type, session_sort, voice_address, saleid, text)
    try:
        sql = """
            insert into
                zt_service_cust_sessionstorag(typeid,`text`,voice,create_datetime,saleid,session_sort)
            values('{quality_type}','{text}','{voice_address}',now(),'{saleid}','{session_sort}')
            """.format(quality_type=quality_type, text=text, voice_address=voice_address, saleid=saleid,
                       session_sort=session_sort)
        id = conn.mysql_insertid(sql, dbname, '')
        return robotsql.backresult(1)
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        web_logger.error(traceback.format_exc())
        return robotsql.backresult(-1)


# 电话聊天
# 有问题请咨询  WX:T520c1314t
@app.route('/getanswerphone')
def getanswerphone():
    web_logger.info('')
    web_logger.info(request.full_path)
    global dbname
    try:
        if not 'companyid' in request.values or not 'text' in request.values \
                or not 'cid' in request.values or not 'channelid' in request.values \
                or not 'clevel' in request.values or not 'location' in request.values \
                or not 'who' in request.values or not 'choiceback' in request.values \
                or not 'serviceid' in request.values or not 'operation' in request.values \
                or not 'questionid' in request.values or not 'robot' in request.values \
                or not 'storagetext' in request.values or not 'storagevoice' in request.values \
                or not 'createtime' in request.values or not 'question' in request.values \
                or not 'answer' in request.values or not 'cid' in request.values:
            return robotsql.backtypeaddphone(0, -1, 1, '缺少参数！！请检查参数是否齐全！！', '', 'close', '', -1, "", "", "", '', '', '',
                                             '', '', '', '', '', '', '', '')  # 557788

        cid = request.values['cid']  # 会话编码
        serviceid = request.values['serviceid']  # 模块类型
        text = request.values['text']  # 查询文本
        companyid = request.values['companyid']  # 公司编码
        channelid = request.values['channelid']  # 渠道编码
        clevel = request.values['clevel']  # 客户级别
        location = request.values['location']  # 地理位置
        who = request.values['who']  # 访问者，1：用户2：客服
        choiceback = request.values['choiceback']  # 上次返回的调用
        # （1：开场白 2：终止通话 3：正常提问  4：主动提问 5:中断 6：保存聊天记录7.训练机器人 ）
        operation = request.values['operation']
        askid = request.values['questionid']  # 主动提问编码
        robot = request.values['robot']  # 是否是机器人  1是
        storagetext = request.values['storagetext']
        storagevoice = request.values['storagevoice']  #
        createtime = request.values['createtime']  # 会话时间
        answer = request.values['answer']  # 学习的答案
        question = request.values['question']  # 学习的问题
        userid = ""  # 任务编码
        get_digits = request.values['get_digits']
        answerattitude = ""  # 答案态度
        collectid = ""  # 采集信息编码
        if 'answerattitude' in request.values:
            answerattitude = request.values['answerattitude']
        # backspecial = ''
        if 'collectid' in request.values:
            collectid = request.values['collectid']
        session_data = ""  # 聊天编码
        session_sort = ""  # 会话顺序
        if 'session_data' in request.values:
            session_data = request.values['session_data']
        if 'session_sort' in request.values:
            session_sort = request.values['session_sort']
        if 'userid' in request.values:
            userid = request.values['userid']
        peplesex = ''
        if 'sex' in request.values:
            peplesex = request.values['sex']
        if 'dbname' in request.values:
            dbname = request.values['dbname']
        else:
            ip = request.host  # remote_addr
            dbname = robotsql.get_dbname(ip, dbname)
        sharecmpid = ''
        if 'sharecmpid' in request.values:
            sharecmpid = request.values['sharecmpid']
        web_logger.info('cid:%s text:%s operation:%s serviceid:%s companyid:%s storagevoice:%s channelid:%s clevel:%s '
                        'location:%s who:%s choiceback:%s askid:%s robot:%s storagetext:%s storagevoice:%s createtime:%s '
                        'answer:%s question:%s userid:%s get_digits:%s answerattitude:%s collectid:%s session_data:%s '
                        'session_sort:%s peplesex:%s dbname:%s sharecmpid:%s',
                        cid, text, operation, serviceid, companyid, storagevoice, channelid, clevel,
                        location, who, choiceback, askid, robot, storagetext, storagevoice, createtime,
                        answer, question, userid, get_digits, answerattitude, collectid, session_data,
                        session_sort, peplesex, dbname, sharecmpid)
        if text != "" and len(text) > 5 and text[-4:] == '.wav':
            datajson = robotsql.Voicerecognition(1, text, time.time())
            data = json.loads(datajson)
            storagevoice = text.replace(conn.voice_dress, '')
            text = data['text']
        web_logger.info('cid:%s text:%s storagevoice:%s operation:%s', cid, text, storagevoice, operation)
        return robotsql.grphone(cid, text, who, companyid, channelid, clevel,
                                location, choiceback, serviceid, operation, askid, robot, storagetext, storagevoice,
                                createtime, question, answer, answerattitude, collectid, session_data, session_sort,
                                userid, peplesex, dbname, sharecmpid, get_digits)

    except Exception as e:
        cid = request.values['cid']  # 会话编码
        web_logger.error('cid:%s error:%s %s', cid, type(e), e)
        web_logger.error(traceback.format_exc())
        session_data = ""
        session_sort = ""
        if 'session_data' in request.values:
            session_data = request.values['session_data']
        if 'session_sort' in request.values:
            session_sort = request.values['session_sort']
        robotsql.weixin_push(cid, str(e), "调用机器人出错！！")
        return robotsql.backtypeaddphone(0, cid, 1, "祝你生活愉快再见！！", '', 'close', '', -1, "", "", "", '', '', '', '', '',
                                         '', '', '', session_data, session_sort, dbname)  # 557788


# 获取语音流
@app.route('/audio_stream')
def audio_stream():
    file = request.values['file']  # 文件名
    try:
        return robotsql.getBody(file)
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        robotsql.weixin_push(file, str(e), "获取录音文件出错！！")
        return ''


# 查询天气
@app.route('/weather')
def weather():
    try:
        city = str(request.values['city'])  # 城市
        city = '深圳'
        if city == '1':
            city = '深圳'
        elif city == '2':
            city = '广州'
        elif city == '3':
            city = '江门'
        data = robotsql.jsonweat(city, 0)
        if data == '':
            data = '查询无果'
        return data

    except:
        return '查询天气出错'


# 电话问题学习
@app.route('/robotstudyphone')
def robotstudyphone():
    pass
    # if not 'cmpid' in request.args or not 'serviceid' in request.args \
    #         or not 'question' in request.args or not 'answer' in request.args:
    #     return '参数不正确，请重新输入！'
    # else:
    #     try:
    #
    #         cmpid = request.values['cmpid']  # 公司编码
    #         serviceid = request.values['serviceid']  # 服务
    #         question = request.values['question']  # 问题
    #         answer = request.values['answer']  # 答案
    #         robotsql.writetxt('phoneaddquestion',
    #                           'question ' + time.strftime('%Y-%m-%d %H-%M-%S') + ' ' + ' 公司编码：' + str(
    #                               cmpid) + ' ' + '问题: ' +
    #                           str(question) + ' ' + ' 答案：' + str(answer) + ' ' + ' 服务：' + str(serviceid))
    #
    #         answerid = robotsql.insertanswer(cmpid, answer,dbname,cid)
    #         insertcount = '-1'
    #         if answerid != conn.err:
    #             mongorobot.addstatement(str(cmpid), question, 'A' + str(answerid), 'service' + str(serviceid))
    #             insertcount = robotsql.insertquestion(cmpid, question, answerid, serviceid)
    #
    #         return str(insertcount)
    #
    #     except Exception as e:
    #         robotsql.writetxt('memcachtxt', 'robotstudyphoneerr ' + ' ' + str(datetime.datetime.now()) + ' ' + str(e))
    #         return '-1'


# 读取IM常见问题
@app.route('/comquestion')
def comquestion():
    global dbname
    try:
        if not 'token' in request.args \
                or not 'cid' in request.args or not 'channelid' in request.args \
                or not 'clevel' in request.args or not 'location' in request.args:
            cid = request.args['cid']  # 会话编码
            return robotsql.backtype(0, cid, 1, '缺少参数！！请检查参数是否齐全！！')
        else:
            token = request.args['token']  # token
            cid = request.args['cid']  # 会话编码
            channelid = request.args['channelid']  # 渠道编码
            clevel = request.args['clevel']  # 客户级别
            location = request.args['location']  # 地理位置
            # 返回公司编码

            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            cmpid = robotsql.getcmpid(token, dbname, cid)
            web_logger.info('cid:%s dbname:%s cmpid:%s' % (cid, dbname, cmpid))
            # 判断公司编码是否有效
            if cmpid != '' and cmpid != conn.err:
                # 插入调用机器人记录并返回编码
                sessionid = robotsql.insetCallrecords(
                    cid, "常见问题", 1, cmpid, channelid, clevel, location, dbname)
                # 判断插入是否成功
                if sessionid != 0 and sessionid != conn.err:
                    question = robotsql.comquestion(cmpid, dbname, cid)
                    backcon = robotsql.backtype(1, cid, 2, question)
                    # 插入回答记录
                    sufins = robotsql.insertbackrecord(
                        sessionid, 1, 2, backcon, dbname, cid)
                    if sufins > 0:
                        return backcon
                    else:
                        return robotsql.backtype(0, cid, 1, "插入返回数据失败！")
                else:
                    return robotsql.backtype(0, cid, 1, '插入调用机器人记录失败！')
            else:
                return robotsql.backtype(0, cid, 1, notcmpid)
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return robotsql.backtype(0, -1, 1, '读取常见问题错误！！')


# 添加公司问题库和机器人问题库
@app.route('/addknowquestion')
def addknowquestion():
    global dbname
    if not 'cmpid' in request.values \
            or not 'question' in request.values or not 'answer' in request.values:
        return '参数不正确，请重新输入！'
    else:
        try:
            mindatabasename = ''
            cmpid = request.values['cmpid']  # 公司编码
            question = request.values['question']  # 问题
            answer = request.values['answer']  # 答案

            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            web_logger.info('cmpid:%s question:%s answer:%s dbname:%s' % (
                cmpid, question, answer, dbname))
            if question != '':
                if cmpid.count('-') == 1:
                    data = cmpid.split('-')
                    cmpid = data[0]
                    mindatabasename = data[1]

                mongorobot.addstatement(
                    cmpid, question, answer, mindatabasename, dbname)
            return 'true'
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return 'false'


# 删除文字与包含的答案编码（通常编辑的时候java全部删除后再重新添加）
@app.route('/delquestion')
def delquestion():
    global dbname
    if not 'cmpid' in request.args \
            or not 'deldata' in request.args:
        return '参数不正确，请重新输入！'
    else:
        try:
            newdatabasename = ''
            cmpid = request.args['cmpid']  # 公司编码
            deldata = request.args['deldata']  # 要删除的数据
            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            web_logger.info('cmpid:%s question:%s  dbname:%s' %
                            (cmpid, deldata, dbname))
            if cmpid.count('-') == 1:
                data = cmpid.split('-')
                cmpid = data[0]
                newdatabasename = data[1]
            mongodbcon.deldata_id(cmpid, deldata, newdatabasename, dbname)
            return str(1)

        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return '-1'


@app.route('/addcloseresul')
def addcloseresul():
    try:
        # a.answer ,a.answertypeid
        id = request.values['id']  # 公司编码
        closeresul = request.values['closeresul']  # 问题

        mongorobot.addcallresults(id, closeresul)

        return 'true'
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return 'false'


@app.route('/addanswertype')
def addanswertype():
    try:
        # a.answer ,a.answertypeid
        answertyelist = robotsql.selanswertypeformongodb('', '')
        for answertye in answertyelist:
            if answertye[0] != "":
                mongorobot.addanswertype(str(answertye[1]), str(answertye[0]))
        return 'true'
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return 'false'


# 添加全局态度
@app.route('/addanswertypecommon')
def addanswertypecommon():
    if not 'answer' in request.values \
            or not 'answertypeid' in request.values:
        return '参数不正确，请重新输入！'
    else:
        try:

            answer = request.values['answer']
            answertypeid = request.values['answertypeid']
            answerdata = answer.split(',')
            for answerdatanum in answerdata:
                if answerdatanum != "":
                    mongorobot.addanswertype(answertypeid, answerdatanum)
                    web_logger.info('answertypeid:%s answerdatanum:%s' % (
                        answertypeid, answerdatanum))
            return '1'
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return '-1'


# 删除全局态度
@app.route('/delanswertypecommon')
def delanswertypecommon():
    if not 'answer' in request.values \
            or not 'answertypeid' in request.values:
        return '参数不正确，请重新输入！'
    else:
        try:

            answer = request.values['answer']
            answertypeid = request.values['answertypeid']
            answerdata = answer.split(',')

            for answerdatanum in answerdata:
                if answerdatanum != "":
                    mongodbcon.delcommon(answertypeid, answerdatanum)
                web_logger.info('answertypeid:%s answerdatanum:%s' %
                                (answertypeid, answerdatanum))
            return '1'
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return '-1'


# 查询常见问题
@app.route('/getquestionid')
def getquestionid():
    global dbname
    try:
        if not 'token' in request.args or not 'questionid' in request.args \
                or not 'cid' in request.args or not 'channelid' in request.args \
                or not 'clevel' in request.args or not 'location' in request.args:
            cid = request.args['cid']  # 会话编码
            return robotsql.backtype(0, cid, 1, '缺少参数！！请检查参数是否齐全！！')
        else:
            questionid = request.args['questionid']  # 问题编码
            token = request.args['token']  # token
            cid = request.args['cid']  # 会话编码
            channelid = request.args['channelid']  # 渠道编码
            clevel = request.args['clevel']  # 客户级别
            location = request.args['location']  # 地理位置

            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            cmpid = robotsql.getcmpid(token, dbname, cid)
            web_logger.info('questionid:%s cmpid:%s dbname:%s' %
                            (questionid, cmpid, dbname))

            # 判断公司编码是否有效
            if cmpid != '' and cmpid != conn.err:
                sessionid = robotsql.insetCallrecords(
                    cid, questionid, 2, cmpid, channelid, clevel, location, dbname)
                # 判断插入是否成功
                sufins = 0
                backcon = ''
                if sessionid != 0 and sessionid != conn.err:
                    backcon = robotsql.fromquesidtoans(questionid, dbname, cid)
                    sufins = robotsql.insertbackrecord(
                        sessionid, 1, 1, backcon, dbname, cid)
                if sufins > 0:
                    return robotsql.backtype(1, cid, 1, backcon)
                else:
                    return robotsql.backtype(0, cid, 1, "插入返回数据失败！")
            else:
                return robotsql.backtype(0, cid, 1, notcmpid)
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return robotsql.backtype(0, -1, 1, "查询常见问题答案出错！！")


# 查询特定常见问题答案
@app.route('/getquestionnum')
def getquestionnum():
    global dbname
    try:
        if not 'token' in request.args or not 'num' in request.args \
                or not 'cid' in request.args or not 'channelid' in request.args \
                or not 'clevel' in request.args or not 'location' in request.args:
            cid = request.args['cid']  # 会话编码
            return robotsql.backtype(0, -1, 1, '缺少参数！！请检查参数是否齐全！！')
        else:
            num = request.args['num']  # 序号
            token = request.args['token']  # token
            cid = request.args['cid']  # 会话编码
            channelid = request.args['channelid']  # 渠道编码
            clevel = request.args['clevel']  # 客户级别
            location = request.args['location']  # 地理位置

            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            cmpid = robotsql.getcmpid(token, dbname, cid)

            web_logger.info('num:%s cmpid:%s dbname:%s' % (num, cmpid, dbname))
            # 判断公司编码是否有效
            if cmpid != '' and cmpid != conn.err:
                sessionid = robotsql.insetCallrecords(
                    cid, num, 2, cmpid, channelid, clevel, location, dbname)
                # 判断插入是否成功
                sufins = 0
                backcon = ''
                if sessionid != 0 and sessionid != conn.err:
                    backcon = robotsql.fromquestionnum(num, cmpid, dbname, cid)
                    sufins = robotsql.insertbackrecord(
                        sessionid, 1, 1, backcon, dbname, cid)
                if sufins > 0:
                    return robotsql.backtype(1, cid, 1, backcon)
                else:
                    return robotsql.backtype(0, cid, 1, "插入返回数据失败！")
            else:
                return robotsql.backtype(0, cid, 1, notcmpid)

    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return robotsql.backtype(0, -1, 1, "查询常见问题答案出错！！")


# 添加公共行业问题库
@app.route('/addindustrycommon')
def addindustryncommon():
    if not 'industryid' in request.args or not 'industryquestion' in request.args \
            or not 'industryanswerid' in request.args:
        return '参数不正确，请重新输入！'
    else:
        try:

            industryid = request.values['industryid']  # 行业库编码
            industryquestion = request.values['industryquestion']  # 公共问题
            industryanswerid = request.values['industryanswerid']  # 答案编码  CQ
            web_logger.info('industryid:%s industryquestion:%s industryanswerid:%s' % (
                industryid, industryquestion, industryanswerid))
            if industryquestion != "":
                mongorobot.addtradequestioncommon(
                    industryid, industryquestion, industryanswerid)
            # else:
            #     mongorobot.addtradequestioncommon(industryid, industryquestion, industryanswerid)
            return 'true'
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return 'false'


# 删除公共行业问题库(初始使用的是问题和答案分开删除)
@app.route('/delindustrycommon')
def delindustrycommon():
    if not 'industryid' in request.args or not 'industryquestion' in request.args:
        return '参数不正确，请重新输入！'
    else:
        try:

            industryid = request.values['industryid']  # 行业库编码
            industryquestion = request.values['industryquestion']  # 公共问题
            industryanswerid = ''  # 答案编码  A
            web_logger.info('industryid:%s industryquestion:%s industryanswerid:%s' % (
                industryid, industryquestion, industryanswerid
            ))
            if industryquestion != "":
                mongodbcon.delcommondata(industryid, industryquestion)
            # else:
            #     mongodbcon.delcommondata(industryid, industryquestion)
            # mongodbcon.delindustryquestion(industryid,industryquestion,industryanswerid)

            return '1'
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return '-1'


# 添加主流程态度
@app.route('/specialanswer')
def specialanswer():
    global dbname
    if not 'hoodleMobile' in request.args or not 'words' in request.args \
            or not 'cmpid' in request.args or not 'attitude' in request.args:
        return '参数不正确，请重新输入！'
    else:
        try:

            cmpid = request.values['cmpid']  # 公司编码
            HoodleMobile = request.values['hoodleMobile']  # 主动提问问题编码
            words = request.values['words']  # 答案
            attitude = request.values['attitude']  # 答案类别
            # print('dddff')
            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            if words != "":
                words = words.split(',')
                for word in words:
                    mongorobot.addspecial(
                        cmpid, HoodleMobile, word, attitude, dbname)
            # mongodbcon.dropTable('database'+str(cmpid)+'-HoodleMobile'+str(HoodleMobile))
            # if words == "":
            #     mongorobot.addspecial(cmpid, HoodleMobile, '', attitude,dbname)
            # else:
            #     words = words.split(',')
            #     for word in words:
            #         mongorobot.addspecial(cmpid, HoodleMobile, word, attitude,dbname)
            return '1'
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return '-1'


# 删除主流程态度
@app.route('/delspecialword')
def delspecialword():
    global dbname
    if not 'cmpid' in request.args or not 'hoodleMobile' in request.args or not 'attitude' in request.args or not 'delword' in request.args:
        return '参数不正确，请重新输入！'
    else:
        try:
            cmpid = request.values['cmpid']  # 公司编码
            hoodleMobile = request.values['hoodleMobile']
            attitude = request.values['attitude']
            delword = request.values['delword']
            delwords = delword.split(',')

            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            for word in delwords:
                mongodbcon.delonedata(
                    cmpid, hoodleMobile, attitude, word, dbname)
            return '1'
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return '-1'


# 查询机器人是否存在
@app.route('/verification')
def verification():
    global dbname
    if not 'cmpid' in request.args or not 'serviceid' in request.args:
        return '参数不正确，请重新输入！'
    else:
        try:
            cmpid = request.values['cmpid']  # 公司编码
            serviceid = request.values['serviceid']  # 服务编码

            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host
                dbname = robotsql.get_dbname(ip, dbname)
            robotcount = robotsql.verificationrobot(
                cmpid, serviceid, dbname, '')
            if str(robotcount) != "0":
                return robotsql.backresult(1)
            else:
                return robotsql.backresult(-1)
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            return robotsql.backresult(-1)


# 会话的问答存储
@app.route('/sessionstorage')
def sessionstorage():
    pass
    # if not 'cid' in request.args or not 'storagetext' in request.args \
    #         or not 'storagevoice' in request.args or not 'robot' in request.args \
    #         or not 'createtime' in request.args:
    #     return robotsql.backresult('参数不正确，请重新输入！')
    # else:
    #     try:
    #         cid = request.values['cid']
    #         storagetext = request.values['storagetext']
    #         storagevoice = request.values['storagevoice']
    #         robot = request.values['robot']
    #         createtime = request.values['createtime']
    #         insertcount = robotsql.insertsessionstorage(robot, storagetext, storagevoice, createtime, cid)
    #         return robotsql.backresult(insertcount)
    #     except Exception as e:
    #         robotsql.writetxt('memcachtxt', 'sessionstorageerr ' + ' ' + str(datetime.datetime.now()) + ' ' + str(e))
    #         return robotsql.backresult('-1')


# 三次机器人问题库与态度（已不用）
@app.route('/removetable')
def removetable():
    try:
        serviceid = ''
        hoodleMobile = ''
        if 'hoodleMobile' in request.values:
            hoodleMobile = request.values['hoodleMobile']
        if 'serviceid' in request.values:
            serviceid = request.values['serviceid']
        cmpid = request.values['cmpid']  # 公司编码
        if serviceid != "":
            mongodbcon.dropservice(
                'database' + str(cmpid) + '-service' + str(serviceid))
        if hoodleMobile != "":
            mongodbcon.drophoodleMobile(
                'database' + str(cmpid) + '-HoodleMobile' + str(hoodleMobile))
        return '1'
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return '-1'


# 删除不存在的表(已不用)
@app.route('/delnousetable')
def delnousetable():
    try:

        alltable = mongodbcon.selalltable()
        print(alltable)
        for table in alltable:
            if table == 'admin':
                continue
            # data = mongodbcon.seltable(table)
            # if str(data)=='0' or str(data)=='1':
            # mongodbcon.dropservice(table)
            # if int(data) < 5:
            #     print(table,data)

            if 'HoodleMobile' in table:
                num = table.index('HoodleMobile')
                hoodleMobile = table[num + 12:]

                begin = table.index('database')
                end = table.index('-')
                cmpid = table[:begin + 8:end]
                print('in', table, hoodleMobile, cmpid)

                # count = robotsql.selifinusehoodleMobile(hoodleMobile)
                # print(count)
                # if str(count)!='1':
                print('del   ' + table)
            # mongodbcon.drophoodleMobile(table)

            elif 'service' in table:

                num = table.index('service')
                serviceid = table[num + 7:]

                begin = table.index('database')
                end = table.index('-')
                cmpid = table[:begin + 8:end]
                print('in', table, serviceid)
                print('del   ' + table)
                # mongodbcon.dropservice(table)

        return '1'
    except:
        return '-1'


# 已不用
@app.route('/create')
def create():
    alltable = robotsql.seldata('', '')
    for data in alltable:
        # print('database'+str(data[0]) +'-service'+str(data[1]))
        mongodbcon.dropservice(
            'database' + str(data[0]) + '-service' + str(data[1]))

    return '1'


# 重新更新全部表（已不用）
@app.route('/updataalldata')
def updataalldata():
    pass
    # allrb = robotsql.haverobotincmp(dbname,'')
    # print(allrb)
    #
    # for data in allrb:
    #     # # print(data)
    #     dataname = 'database' + str(data[0]) + '-service' + str(data[1])
    #     mongodbcon.dropservice(dataname)
    #     mongodbcon.dropservice(str(data[0]) + '-service' + str(data[1]))
    #     allquestion = robotsql.selinquestion(str(data[0]), str(data[1]),dbname,'')
    #     # 公司问题库
    #     for que in allquestion:
    #         print(que)#cmpid,question,answer,mindatabasename
    #         mongorobot.addstatement(data[0], que[0], que[1],'',dbname)
    #         # 查询相似问题
    #         samedata = robotsql.selasmequestion(que[2],dbname,'')
    #         for same in samedata:
    #             mongorobot.addstatement(data[0], same[0], que[1],'',dbname)
    #     # # 机器人问答库
    #     mongodbcon.dropservice('database'+str(data[0]) )
    #     allquestion = robotsql.selinquestion(str(data[0]),str(data[1]),dbname,'')
    #     print(allquestion)
    #     for que in allquestion:
    #         print(que)#(cmpid,question,answer,mindatabasename,dbname)
    #         mongorobot.addstatement(str(data[0]) ,que[0],que[1],str(data[0]) + '-service' + str(data[1]),dbname)
    #         #查询相似问题
    #         samedata = robotsql.selasmequestion(que[2],dbname,'')
    #         for same in samedata:
    #             mongorobot.addstatement(str(data[0]),same[0],que[1],str(data[0]) + '-service' + str(data[1]),dbname)
    #     # 机器人态度
    #     allHoodleMobileid = robotsql.selinHoodleMobileid(data[0], data[1],dbname,'')
    #     for HoodleMobileid in allHoodleMobileid:
    #         print(HoodleMobileid[0])
    #         deldataname = 'database' + str(data[0]) + '-HoodleMobile' + str(HoodleMobileid[0])
    #         mongodbcon.drophoodleMobile(deldataname)
    #         print(deldataname)
    #         print(str(data[0]) + '-HoodleMobile' + str(HoodleMobileid[0]))
    #         mongodbcon.drophoodleMobile(str(data[0]) + '-HoodleMobile' + str(HoodleMobileid[0]))
    #         worddata = robotsql.selinatt(HoodleMobileid[0],dbname,'')
    #
    #         for alldata in worddata:
    #             att = alldata[0]
    #             words = alldata[1].split(',')
    #             for word in words:
    #                 # mongorobot.addspecial(cmpid,HoodleMobile,word,attitude)
    #                 print(data[0], HoodleMobileid[0], word, str(att))
    #                 mongorobot.addspecial(data[0], HoodleMobileid[0], word, str(att),dbname)
    #
    # return '1'


# app.run(host="", port=808, debug=True,threaded=True,processes=3)
# app.run(host="", port=8081, debug=True,threaded=True)
# wav翻译
@app.route('/VoiceRecognition')
def VoiceRecognition():
    if not 'industryid' in request.values \
            or not 'file' in request.values:
        return '参数不正确，请重新输入！'
    else:
        try:
            industryid = request.values['industryid']
            file = request.values['file']
            web_logger.info('industryid:%s file:%s', industryid, str(file))
            back = robotsql.Voicerecognition(
                industryid, file, time.time())  # 获取地址信息
            return str(back)
        except Exception as e:
            web_logger.error('file:%s error:%s %s', file, type(e), e)
            file = request.values['file']
            backtuple = {"code": "-1", "text": '', "file": file, 'sex': ''}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon


# 调用百度对话情绪识别接口
@app.route('/getbaidu')
def getbaidu():
    try:
        talk = request.values['talk']
        text = request.values['text']
        return json.dumps(robotsql.getbaidu(talk, text), ensure_ascii=False, sort_keys=True)
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return json.dumps({'err': str(e)}, ensure_ascii=False, sort_keys=True)


# import os
# status = os.system('sh /usr/lzj/Pro/f112.sh /usr/lzj/Pro/lzj.mp3')
# print(status)
# print(status>>16)
# 先将MP3转换为vaw格式再翻译
@app.route('/VoicechangeRecognition')
def VoicechangeRecognition():
    if not 'industryid' in request.values \
            or not 'file' in request.values:
        return '参数不正确，请重新输入！'
    else:
        try:
            industryid = request.values['industryid']
            file = request.values['file']
            web_logger.info('industryid:%s file:%s', industryid, str(file))
            back = robotsql.Voicechangerecognition(
                industryid, file, time.time())
            return str(back)
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            file = request.values['file']
            backtuple = {"code": "-1", "text": '', "file": file}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon


# 翻译并判断是否脏话
@app.route('/VoiceRecognitiondirty')
def VoiceRecognitiondirty():
    if not 'industryid' in request.values \
            or not 'file' in request.values:
        return '参数不正确，请重新输入！'
    else:
        try:
            industryid = request.values['industryid']
            file = request.values['file']
            web_logger.info('industryid:%s file:%s' % (industryid, str(file)))
            back = robotsql.Voicerecognitiondirty(
                industryid, file, time.time())
            return back
        except Exception as e:
            web_logger.error('error:%s %s', type(e), e)
            file = request.values['file']
            backtuple = {"code": "-1", "text": '', "file": file, 'dirty': ''}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon


# 重新整顿mongodb数据库
# @app.route('/reformingdatabase')
# def reformingdatabase():
#     robotsql.thread_install_mongodbss(dbname)
#     # 问答库
#     # allrb = robotsql.haverobotincmp(dbname,'')
#     # for data in allrb:
#     #     mongodbcon.dropservice(str(dbname)+'database' + str(data[0]))
#         # #添加公司问题库
#         # allquestion = robotsql.selinquestion(str(data[0]), str(data[1]),dbname,'')
#         # for que in allquestion:
#         #     print(data[0], que[0], que[1])
#         #     if que!="":
#         #         mongorobot.addstatement(str(data[0]), que[0], que[1], '',dbname)
#         #     # 查询相似问题
#         #     samedata = robotsql.selasmequestion(que[2],dbname,'')
#         #     for same in samedata:
#         #         if same!="":
#         #             mongorobot.addstatement(str(data[0]), same[0], que[1], '',dbname)
#         # #添加机器人问题库
#         # allrb22 = robotsql.haverobotincmpservice(data[0],dbname,'')
#         # for data1 in allrb22:
#         #     # 服务问题库
#         #     dataname = 'database' + str(data1[0]) + '-service' + str(data1[1])
#         #
#         #     print('dataname', dataname)
#         #     allquestion = robotsql.selinservicequestion(str(data1[0]), str(data1[1]),dbname,'')
#         #     # 问题库
#         #     print('allquestion', allquestion)
#         #     for que in allquestion:
#         #         print('que', que)
#         #         mongorobot.addstatement(str(data1[0]), que[0], que[1], 'service' + str(data1[1]),dbname)
#         #         # 查询相似问题
#         #         samedata = robotsql.selasmequestion(que[2],dbname,'')
#         #         for same in samedata:
#         #             if same!="":
#         #                 mongorobot.addstatement(str(data1[0]), same[0], que[1], 'service' + str(data1[1]),dbname)
#         #     # 添加机器人主流程态度
#         #     allHoodleMobileid = robotsql.selinHoodleMobileid(data1[0], data1[1],dbname,'')
#         #     for HoodleMobileid in allHoodleMobileid:
#         #         deldataname = 'database' + str(data1[0]) + '-HoodleMobile' + str(HoodleMobileid[0])
#         #         worddata = robotsql.selinatt(HoodleMobileid[0],dbname,'')
#         #         for alldata in worddata:
#         #             att = alldata[0]
#         #             if alldata[1] == None:
#         #                 pass
#         #             else:
#         #                 words = alldata[1].split(',')
#         #                 for word in words:
#         #                     print(data1[0], HoodleMobileid[0], word, str(att))
#         #                     if word!="":
#         #                         mongorobot.addspecial(data1[0], HoodleMobileid[0], word, str(att),dbname)
#     return '1'


# 重新添加行业库
@app.route('/insertind')
def insertind():
    allrb = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)
    for data in allrb:
        print('industry', data)
        dataname = 'industry' + str(data)
        mongodbcon.dropservice(dataname)
        print(dataname)
        allquestion = robotsql.selindu(data, '', '')
        # 问题库
        print(allquestion)
        for que in allquestion:
            print(que)
            mongorobot.addindustry(
                data, que[0], que[1], 'industry' + str(data))
            # 查询相似问题
            samedata = robotsql.selasmequestion(que[2], '', '')
            for same in samedata:
                print(same)
                mongorobot.addindustry(
                    data, same[0], que[1], 'industry' + str(data))
    return '1'


# 添加脏话
@app.route('/adddirty')
def adddirty():
    try:
        # a.answer ,a.answertypeid
        text = request.values['text'].strip()  #
        # type = request.values['type'] #
        result = robotsql.add_dirt_txt(text, '', '')
        return result
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return 'false'


# 删除脏话
@app.route('/deldirty')
def deldirty():
    try:
        # a.answer ,a.answertypeid
        text = request.values['text'].strip()  #
        # type = request.values['type'] #
        result = robotsql.del_dirt_txt(text, '', '')
        return result
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return 'false'


@app.route('/seldirty')
def seldirty():
    try:
        # a.answer ,a.answertypeid
        text = request.values['text'].strip()  #
        pagesize = request.args['pagesize']  # 开始行数
        page = request.args['page']  # 结束行数
        time = request.args['time']  # 结束行数
        # type = request.values['type'] #
        result = robotsql.sel_dirt_txt(text, pagesize, page, time, '', '')
        return result
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        backtuple = {'code': str(-1), 'dirtylist': []}
        backcon = json.dumps(backtuple, ensure_ascii=False)
        return backcon


@app.route('/seldirtycount')
def seldirtycount():
    try:
        # a.answer ,a.answertypeid
        text = request.values['text'].strip()  #
        time = request.values['time'].strip()  #
        # type = request.values['type'] #
        result = robotsql.sel_dirt_txt_count(text, time, '', '')
        return result
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        backtuple = {'code': str(-1), 'dirtylist': 0}
        backcon = json.dumps(backtuple, ensure_ascii=False)
        return backcon


# 重新获取
@app.route('/againgetdirty')
def againgetdirty():
    try:
        # a.answer ,a.answertypeid
        robotsql.get_dirt_txt('', '')
        return 'true'
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return 'flase'


# 批量导入问题
@app.route('/addquestionstest', methods=["GET", "POST"])
def addquestionstest():
    global dbname
    try:
        if not "serviceid" in request.values:
            return robotsql.backquestion(10001, "参数不正确，请重新输入")
        serviceid = request.values['serviceid']  # 获取到服务编码
        filetxt = request.files.get("file")  # 获取文本信息
        if 'dbname' in request.values:
            dbname = request.values['dbname']
        else:
            ip = request.host
            dbname = robotsql.get_dbname(ip, dbname)
        web_logger.info('serviceid:%s dbname:%s' % (serviceid, dbname))

        # filetxt = filetxt  # 因为前端传过来的都是二进制流，所以需要先转换成十进制，Windows下默认是gbk
        cmpid = robotsql.selcmpid(serviceid, dbname, '')  # 公司编码

        backda = robotsql.IMphone_thread(cmpid, filetxt, serviceid, dbname, '')

        return robotsql.backquestion(10000, "导入数据成功" + str(serviceid))
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        return robotsql.backquestion(10001, "接口调用错误" + str(e))


# 电话IM测试
@app.route('/addquestiontest', methods=["GET", "POST"])
def addquestiontest():
    global dbname
    try:
        cid = request.values['cid']  # 会话编码
        if not 'companyid' in request.values or not 'text' in request.values \
                or not 'cid' in request.values or not 'channelid' in request.values \
                or not 'clevel' in request.values or not 'location' in request.values \
                or not 'who' in request.values or not 'choiceback' in request.values \
                or not 'serviceid' in request.values or not 'operation' in request.values \
                or not 'questionid' in request.values or not 'robot' in request.values \
                or not 'storagetext' in request.values or not 'storagevoice' in request.values \
                or not 'createtime' in request.values or not 'question' in request.values \
                or not 'answer' in request.values:
            backtuple = {"code": str(-1),
                         "questionid": '', "content": '参数错误', "conversation": '', 'collectid': ''}
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon
        else:
            serviceid = request.values['serviceid']  # 模块类型
            text = request.values['text']  # 查询文本
            cmpid = request.values['companyid']  # 公司编码
            channelid = request.values['channelid']  # 渠道编码
            clevel = request.values['clevel']  # 客户级别
            location = request.values['location']  # 地理位置
            who = request.values['who']  # 访问者，1：用户2：客服
            choiceback = request.values['choiceback']  # 上次返回的调用
            # （1：创建新会话 2：终止通话 3：正常提问  4：主动提问 5:中断 6：保存聊天记录7.训练机器人 ）
            operation = request.values['operation']
            askid = request.values['questionid']  # 主动提问编码
            robot = request.values['robot']  # 是否是机器人  1是
            storagetext = request.values['storagetext']
            storagevoice = request.values['storagevoice']  #
            createtime = request.values['createtime']  # 会话时间
            answer = request.values['answer']  # 学习的答案
            question = request.values['question']  # 学习的问题

            userid = ""  # 任务编码
            answerattitude = ""  # 答案态度
            collectid = ""  # 采集信息编码
            if 'answerattitude' in request.values:
                answerattitude = request.values['answerattitude']
            if 'collectid' in request.values:
                collectid = request.values['collectid']
            if 'userid' in request.values:
                userid = request.values['userid']

            if 'dbname' in request.values:
                dbname = request.values['dbname']
            else:
                ip = request.host  # remote_addr
                dbname = robotsql.get_dbname(ip, dbname)

            IMphonejson = robotsql.grphone(cid, text, who, cmpid, channelid, clevel,
                                           location, choiceback, serviceid, operation, askid, robot, storagetext,
                                           storagevoice,
                                           createtime, question, answer, answerattitude, collectid, '', '',
                                           userid, '', dbname, '')
            IMphonedict = json.loads(IMphonejson)
            backtype = IMphonedict['backtype']
            content = IMphonedict['backanswer']

            if backtype == "9" or backtype == "11":
                content = IMphonedict['memo']

            backtuple = {"code": str(IMphonedict['code']),
                         "questionid": str(IMphonedict['questionid']), "content": str(content),
                         "conversation": str(IMphonedict['conversation']), "collectid": str(IMphonedict['collectid'])
                         }
            backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
            return backcon
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        backtuple = {"code": str(-1),
                     "questionid": '', "content": '', "conversation": '', 'collectid': ''}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon


@app.route('/single_quality_test')
def single_quality_test():
    """
    以 taskid sampleid cmpid 为条件，
    对任务中的单条���音文件进行质检
    """
    task_id = request.values['taskid']  # 任务编码
    sample_id = request.values['sampleid']  # 任务内单条录音的编码
    cmp_id = request.values['cmpid']  # 公司编码
    service_type = request.values['service_type']  # 质检录音类型 #5通话 6IM 7机器人
    try:
        web_logger.info('task_id:%s  cmp_id:%s sample_id:%s service_type:%s',
                        task_id, cmp_id, sample_id, service_type)
        # 开始质检任务
        quality_task_start_key = '%sbeginsampleid%s' % (
            conn.basedbname, sample_id)
        # 过滤已开始的任务，避免重复提交
        if robotsql.memcachcon.if_exist(quality_task_start_key) is None:
            robotsql.memcachcon.set_cach_not_time(quality_task_start_key, 1)
            # 启动线程开始质检任务
            thread_time_thing = robotsql.ThreadWithReturnValue(target=begin_single_quality_task,
                                                               args=(task_id, cmp_id, sample_id))
            thread_time_thing.start()
        back_dict = {"code": str(1), "memo": ''}
        back_json = json.dumps(back_dict, ensure_ascii=False, sort_keys=True)
        robotsql.memcachcon.del_cach(
            '%sbeginsampleid%s' % (conn.basedbname, sample_id))
        return back_json
    except Exception as e:
        robotsql.memcachcon.del_cach(
            '%sbeginsampleid%s' % (conn.basedbname, sample_id))
        web_logger.error('error:%s %s', type(e), e)
        back_dict = {"code": str(-1), "memo": str(e)}
        back_json = json.dumps(back_dict, ensure_ascii=False, sort_keys=True)
        robotsql.weixin_push(task_id, str(e), "开始质检出错！！")
        return back_json


@app.route('/quality_test')
def quality_test():
    """
    以 taskid cmpid 为条件，
    对任务中的单条录音文件进行质检
    :return:
    """
    task_id = request.values['taskid']  # 任务编码
    cmp_id = request.values['cmpid']  # 公司编码
    service_type = request.values['service_type']  # 质检录音类型 #5通话 6IM 7机器人
    try:
        begin_task = robotsql.memcachcon.if_exist(
            '{}begin_quality_test_task{}'.format(conn.basedbname, task_id))
        web_logger.info('task_id:%s cmp_id:%s service_type:%s begin_task:%s ',
                        task_id, cmp_id, service_type, begin_task)

        print(begin_task)
        time.sleep(10)  # Java 数据还未Commit
        if begin_task != 'True':
            begin_quality_task_memcached(task_id, cmp_id, 'True')
            quality_data_dict = []
            if service_type == '5':
                quality_data_dict = get_task_quality_service_data(
                    task_id=task_id, state=0)
            elif service_type == '7':
                quality_data_dict = get_taskid_quality_robot_data(
                    task_id=task_id, state=0)
            web_logger.info('task_id = %s quality_data_dict = %s service_type = %s -> type %s',
                            task_id, quality_data_dict, service_type, type(service_type))
            cycle_translate_voice(quality_data_dict, task_id)
            thread_time_thing = robotsql.ThreadWithReturnValue(
                target=begin_quality_task, args=(task_id, cmp_id))
            thread_time_thing.start()
        else:
            return ''
        backtuple = {"code": str(1), "memo": ''}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon
    except Exception as e:
        robotsql.memcachcon.del_cach(
            '{}begin_quality_test_task{}'.format(conn.basedbname, task_id))
        web_logger.error('error:%s %s', type(e), e)
        backtuple = {"code": str(-1), "memo": str(e)}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        robotsql.weixin_push(task_id, str(e), "开始质检出错！！")
        return backcon


# 智能质检任务暂停接口
@app.route('/quality_test_pause')
def quality_testing_pause():
    taskid = request.values['taskid']  # 任务编码
    try:
        cmpid = request.values['cmpid']  # 公司编码
        web_logger.info('taskid:%s cmpid:%s', taskid, cmpid)
        begin_quality_task_memcached(taskid, cmpid, 'False')
        backtuple = {"code": str(1), "memo": ''}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        robotsql.weixin_push(taskid, str(e), "暂停质检出错！！")
        backtuple = {"code": str(-1), "memo": str(e)}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon


# 在线质检接口
@app.route('/The_online_inspection', methods=["GET", "POST"])
def The_online_inspection():
    sessionid = ''
    try:
        sessionid = request.values['sessionid']  # 通话编码
        # 类型1.开始通话2.结束通话3.主叫录音4.被叫录音
        quality_type = request.values['quality_type']
        call_numb = request.values['call_numb']  # 主叫号码
        called_numb = request.values['called_numb']  # 被叫号码
        unix_begin_time = request.values['unix_begin_time']  # 开始时间(片段录音用时间戳)
        unix_end_time = request.values['unix_end_time']  # 结束时间(片段录音用时间戳)
        voice_address = request.values['voice_address']  # 录音地址
        in_out = request.values['in_out']  # 呼入呼出 1呼入2呼出
        cause = request.values['cause']  # 0客户断开 1坐席断开
        web_logger.info('quality_type:%s call_numb:%s called_numb:%s unix_begin_time:%s unix_end_time:%s '
                        'voice_address:%s sessionid:%s in_out:%s cause:%s',
                        quality_type, call_numb, called_numb, unix_begin_time, unix_end_time, voice_address,
                        sessionid, in_out, cause)
        is_hangoff = online_inspection(int(quality_type), call_numb, called_numb, unix_begin_time, unix_end_time,
                                       voice_address, in_out, sessionid, cause)
        backtuple = {"code": str(1), "memo": '', 'sessionid': str(
            sessionid), 'instruct': str(is_hangoff)}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        web_logger.info('backtuple:%s' % backtuple)
        return backcon
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        robotsql.weixin_push(sessionid, str(e), "在线质检出错！！")
        backtuple = {"code": str(-1), "memo": str(e),
                     'sessionid': str(sessionid), 'instruct': str(0)}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon


# 在线质检接口挂断接口
@app.route('/The_online_inspection_hangup', methods=["GET", "POST"])
def The_online_inspection_hangup():
    sampleid = ''
    try:
        sampleid = request.values['sampleid']  # 通话编码

        online_inspection_hangup(sampleid)
        backtuple = {"code": str(1), "memo": '', 'sessionid': str(
            sampleid), 'instruct': str(1)}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        web_logger.info('sampleid:%s backtuple:%s' % (sampleid, backtuple))
        return backcon
    except Exception as e:
        web_logger.error('error:%s %s', type(e), e)
        robotsql.weixin_push(sampleid, str(e), "在线质检出错！！")
        backtuple = {"code": str(-1), "memo": str(e),
                     'sessionid': str(sampleid), 'instruct': str(0)}
        backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)
        return backcon
